import { defineStore } from 'pinia'
import { reservationApi } from '@/api/reservation'
import { ElMessage } from 'element-plus'

export const useReservationStore = defineStore('reservation', {
  state: () => ({
    // 预约列表数据
    reservations: [],
    // 当前选中的预约
    currentReservation: null,
    // 加载状态
    loading: false,
    exportLoading: false,
    // 分页状态
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0
    },
    // 筛选条件
    filterParams: {
      keyword: '', // 搜索关键词（用户姓名或联系电话）
      status: '', // 状态筛选
      scenicId: '', // 景点筛选
      dateRange: [], // 预约时间范围
      visitorsRange: [], // 游客人数范围
      createDateRange: [] // 创建时间范围
    },
    // 预约状态选项
    statusOptions: [
      { value: 'pending', label: '待确认', color: '#E6A23C' },
      { value: 'confirmed', label: '已确认', color: '#67C23A' },
      { value: 'cancelled', label: '已取消', color: '#F56C6C' },
      { value: 'completed', label: '已完成', color: '#909399' }
    ],
    // 批量操作选中的预约ID
    selectedReservationIds: [],
    // 统计数据
    statistics: {
      todayReservations: 0,
      weekReservations: 0,
      monthReservations: 0,
      totalVisitors: 0
    }
  }),

  getters: {
    // 获取待确认预约
    pendingReservations: (state) => state.reservations.filter(res => res.status === 'pending'),
    
    // 获取已确认预约
    confirmedReservations: (state) => state.reservations.filter(res => res.status === 'confirmed'),
    
    // 获取已取消预约
    cancelledReservations: (state) => state.reservations.filter(res => res.status === 'cancelled'),
    
    // 获取已完成预约
    completedReservations: (state) => state.reservations.filter(res => res.status === 'completed'),
    
    // 按景点分组的预约
    reservationsByScenic: (state) => {
      const grouped = {}
      state.reservations.forEach(res => {
        const scenicName = res.scenicName || '未知景点'
        if (!grouped[scenicName]) {
          grouped[scenicName] = []
        }
        grouped[scenicName].push(res)
      })
      return grouped
    },
    
    // 预约统计信息
    reservationStats: (state) => {
      const stats = {
        total: state.reservations.length,
        pending: 0,
        confirmed: 0,
        cancelled: 0,
        completed: 0,
        totalVisitors: 0,
        avgVisitorsPerReservation: 0
      }
      
      state.reservations.forEach(res => {
        stats[res.status] = (stats[res.status] || 0) + 1
        stats.totalVisitors += res.visitorsCount || 0
      })
      
      stats.avgVisitorsPerReservation = stats.total > 0 
        ? Math.round(stats.totalVisitors / stats.total * 100) / 100 
        : 0
      
      return stats
    },
    
    // 获取状态选项映射
    statusOptionsMap: (state) => {
      const map = {}
      state.statusOptions.forEach(option => {
        map[option.value] = option
      })
      return map
    }
  },

  actions: {
    // 获取预约列表
    async fetchReservations(params = {}) {
      this.loading = true
      try {
        const queryParams = {
          page: this.pagination.current,
          pageSize: this.pagination.pageSize,
          ...this.filterParams,
          ...params
        }
        
        const response = await reservationApi.getReservations(queryParams)
        this.reservations = response.data || []
        this.pagination.total = response.total || 0
        
        return response
      } catch (error) {
        console.error('获取预约列表失败:', error)
        ElMessage.error('获取预约列表失败')
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取预约详情
    async fetchReservationDetail(id) {
      try {
        const response = await reservationApi.getReservationDetail(id)
        this.currentReservation = response.data
        return response
      } catch (error) {
        console.error('获取预约详情失败:', error)
        ElMessage.error('获取预约详情失败')
        throw error
      }
    },

    // 确认预约
    async confirmReservation(id, notes = '') {
      try {
        await reservationApi.confirmReservation(id, { notes })
        
        // 更新本地预约状态
        const index = this.reservations.findIndex(res => res.id === id)
        if (index !== -1) {
          this.reservations[index].status = 'confirmed'
          this.reservations[index].updateTime = new Date().toISOString()
        }
        
        ElMessage.success('预约确认成功')
      } catch (error) {
        console.error('确认预约失败:', error)
        ElMessage.error('确认预约失败')
        throw error
      }
    },

    // 取消预约
    async cancelReservation(id, reason = '') {
      try {
        await reservationApi.cancelReservation(id, { reason })
        
        // 更新本地预约状态
        const index = this.reservations.findIndex(res => res.id === id)
        if (index !== -1) {
          this.reservations[index].status = 'cancelled'
          this.reservations[index].updateTime = new Date().toISOString()
        }
        
        ElMessage.success('预约取消成功')
      } catch (error) {
        console.error('取消预约失败:', error)
        ElMessage.error('取消预约失败')
        throw error
      }
    },

    // 完成预约
    async completeReservation(id, notes = '') {
      try {
        await reservationApi.completeReservation(id, { notes })
        
        // 更新本地预约状态
        const index = this.reservations.findIndex(res => res.id === id)
        if (index !== -1) {
          this.reservations[index].status = 'completed'
          this.reservations[index].updateTime = new Date().toISOString()
        }
        
        ElMessage.success('预约完成')
      } catch (error) {
        console.error('完成预约失败:', error)
        ElMessage.error('完成预约失败')
        throw error
      }
    },

    // 修改预约信息
    async updateReservation(id, reservationData) {
      try {
        const response = await reservationApi.updateReservation(id, reservationData)
        
        // 更新本地预约数据
        const index = this.reservations.findIndex(res => res.id === id)
        if (index !== -1) {
          this.reservations[index] = { ...this.reservations[index], ...reservationData }
        }
        
        ElMessage.success('预约信息更新成功')
        return response
      } catch (error) {
        console.error('更新预约失败:', error)
        ElMessage.error('更新预约失败')
        throw error
      }
    },

    // 删除预约
    async deleteReservation(id) {
      try {
        await reservationApi.deleteReservation(id)
        
        // 从本地数据中移除预约
        this.reservations = this.reservations.filter(res => res.id !== id)
        this.pagination.total -= 1
        
        ElMessage.success('预约删除成功')
      } catch (error) {
        console.error('删除预约失败:', error)
        ElMessage.error('删除预约失败')
        throw error
      }
    },

    // 批量确认预约
    async batchConfirmReservations(reservationIds, notes = '') {
      try {
        await reservationApi.batchConfirmReservations(reservationIds, { notes })
        
        // 更新本地预约状态
        reservationIds.forEach(id => {
          const index = this.reservations.findIndex(res => res.id === id)
          if (index !== -1) {
            this.reservations[index].status = 'confirmed'
            this.reservations[index].updateTime = new Date().toISOString()
          }
        })
        
        ElMessage.success(`成功确认 ${reservationIds.length} 个预约`)
      } catch (error) {
        console.error('批量确认预约失败:', error)
        ElMessage.error('批量确认预约失败')
        throw error
      }
    },

    // 批量取消预约
    async batchCancelReservations(reservationIds, reason = '') {
      try {
        await reservationApi.batchCancelReservations(reservationIds, { reason })
        
        // 更新本地预约状态
        reservationIds.forEach(id => {
          const index = this.reservations.findIndex(res => res.id === id)
          if (index !== -1) {
            this.reservations[index].status = 'cancelled'
            this.reservations[index].updateTime = new Date().toISOString()
          }
        })
        
        ElMessage.success(`成功取消 ${reservationIds.length} 个预约`)
      } catch (error) {
        console.error('批量取消预约失败:', error)
        ElMessage.error('批量取消预约失败')
        throw error
      }
    },

    // 导出预约数据
    async exportReservations(params = {}) {
      this.exportLoading = true
      try {
        const queryParams = {
          ...this.filterParams,
          ...params
        }
        
        const response = await reservationApi.exportReservations(queryParams)
        
        // 创建下载链接
        const blob = new Blob([response.data], { 
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `预约数据_${new Date().toISOString().split('T')[0]}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        ElMessage.success('预约数据导出成功')
        return response
      } catch (error) {
        console.error('导出预约数据失败:', error)
        ElMessage.error('导出预约数据失败')
        throw error
      } finally {
        this.exportLoading = false
      }
    },

    // 获取预约统计数据
    async fetchReservationStatistics(params = {}) {
      try {
        const response = await reservationApi.getReservationStatistics(params)
        this.statistics = response.data || {}
        return response
      } catch (error) {
        console.error('获取预约统计失败:', error)
        ElMessage.error('获取预约统计失败')
        throw error
      }
    },

    // 搜索预约
    async searchReservations(keyword) {
      this.filterParams.keyword = keyword
      this.pagination.current = 1
      await this.fetchReservations()
    },

    // 按状态筛选预约
    async filterByStatus(status) {
      this.filterParams.status = status
      this.pagination.current = 1
      await this.fetchReservations()
    },

    // 按景点筛选预约
    async filterByScenic(scenicId) {
      this.filterParams.scenicId = scenicId
      this.pagination.current = 1
      await this.fetchReservations()
    },

    // 按日期范围筛选预约
    async filterByDateRange(dateRange) {
      this.filterParams.dateRange = dateRange
      this.pagination.current = 1
      await this.fetchReservations()
    },

    // 按游客人数范围筛选预约
    async filterByVisitorsRange(visitorsRange) {
      this.filterParams.visitorsRange = visitorsRange
      this.pagination.current = 1
      await this.fetchReservations()
    },

    // 综合筛选预约
    async filterReservations(filters) {
      this.filterParams = { ...this.filterParams, ...filters }
      this.pagination.current = 1
      await this.fetchReservations()
    },

    // 重置筛选条件
    resetFilterParams() {
      this.filterParams = {
        keyword: '',
        status: '',
        scenicId: '',
        dateRange: [],
        visitorsRange: [],
        createDateRange: []
      }
    },

    // 设置分页参数
    setPagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination }
    },

    // 设置当前预约
    setCurrentReservation(reservation) {
      this.currentReservation = reservation
    },

    // 清空当前预约
    clearCurrentReservation() {
      this.currentReservation = null
    },

    // 设置选中的预约ID（用于批量操作）
    setSelectedReservationIds(ids) {
      this.selectedReservationIds = ids
    },

    // 添加选中的预约ID
    addSelectedReservationId(id) {
      if (!this.selectedReservationIds.includes(id)) {
        this.selectedReservationIds.push(id)
      }
    },

    // 移除选中的预约ID
    removeSelectedReservationId(id) {
      this.selectedReservationIds = this.selectedReservationIds.filter(selectedId => selectedId !== id)
    },

    // 清空选中的预约ID
    clearSelectedReservationIds() {
      this.selectedReservationIds = []
    },

    // 获取状态标签样式
    getStatusStyle(status) {
      const option = this.statusOptionsMap[status]
      return option ? { color: option.color } : {}
    }
  }
})